package org.hrqing.authorization.security;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationCode;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
import org.springframework.security.oauth2.server.authorization.settings.TokenSettings;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenContext;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenGenerator;

import java.time.Duration;
import java.time.Instant;
import java.util.UUID;

/**
 * @auther Hrqing
 */
public class RandomAuthorizationCodeGenerator implements OAuth2TokenGenerator<OAuth2AuthorizationCode> {

    @Override
    public OAuth2AuthorizationCode generate(OAuth2TokenContext context) {
        if (context.getTokenType() != null && context.getTokenType().equals(new OAuth2TokenType(OAuth2ParameterNames.CODE))) {
            RegisteredClient registeredClient = context.getRegisteredClient();
            TokenSettings tokenSettings = registeredClient.getTokenSettings();

            // 获取令牌有效期
            Duration codeLifetime = tokenSettings.getAuthorizationCodeTimeToLive();

            String codeValue = UUID.randomUUID().toString().split("-")[4];

            return new OAuth2AuthorizationCode(
                    codeValue,
                    Instant.now(),
                    Instant.now().plus(codeLifetime)
            );
        }
        return null;
    }
}
